package comtgl.demo.test;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class TokenBucketRateLimitServiceImpl implements RateLimitService {
    // 存储不同接口的限流器
    private final ConcurrentMap<String, TokenBucketLimiter> limiters = new ConcurrentHashMap<>();
    // 秒级限流速率
    private final int secondRate;
    // 分钟级限流速率
    private final int minuteRate;

    public TokenBucketRateLimitServiceImpl(int secondRate, int minuteRate) {
        this.secondRate = secondRate;
        this.minuteRate = minuteRate;
    }

    @Override
    public boolean tryAccess(String key) {
        // 获取或创建限流器
        TokenBucketLimiter limiter = limiters.computeIfAbsent(
                key,
                k -> new TokenBucketLimiter(secondRate, minuteRate)
        );

        // 尝试获取令牌
        return limiter.tryAcquire();
    }
}